package com.vitogiovanni.tobook;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.ProgressBar;

import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.vitogiovanni.tobook.entity.localeendpoint.Localeendpoint;
import com.vitogiovanni.tobook.entity.localeendpoint.model.Locale;
import com.vitogiovanni.tobook.entity.localeendpoint.model.LocaleCollection;
import com.vitogiovanni.tobook.utilities.LocaleHomeTaskCompleteListener;
import com.vitogiovanni.tobook.utilities.LocaleHomeTaskPreferitiListener;
import com.vitogiovanni.tobook.utilities.NetworkChecker;
import com.vitogiovanni.tobook.utilities.UserEmailFetcher;

public class LocaleActivity extends BaseActivity implements ActionBar.TabListener,
														LocaleHomeTaskCompleteListener<Locale>, LocaleHomeTaskPreferitiListener<List<Locale>>{

	/**
	 * The {@link android.support.v4.view.PagerAdapter} that will provide
	 * fragments for each of the sections. We use a {@link FragmentPagerAdapter}
	 * derivative, which will keep every loaded fragment in memory. If this
	 * becomes too memory intensive, it may be best to switch to a
	 * {@link android.support.v13.app.FragmentStatePagerAdapter}.
	 */
	SectionsPagerAdapter mSectionsPagerAdapter;
	private String idLocale;
	private String nomeLocale;
	private Locale locale;
	private LocaleTask localeTask;
	private PreferitiTask preferitiTask;
	private ActionBar actionBar;
	private boolean preferito = false;
	private String emailUtente;
	List<Locale> localiPreferiti = new ArrayList<Locale>();
	private boolean caricamento = true;
	private ProgressBar progressBar;
	/**
	 * The {@link ViewPager} that will host the section contents.
	 */
	ViewPager mViewPager;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_locale);

		actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		
		Bundle bundle = getIntent().getExtras();
		
		Context context = getApplicationContext();
		CharSequence text = UserEmailFetcher.getEmail(context);
		emailUtente = text.toString();
		
		idLocale = (String) bundle.get("idLocale");
		nomeLocale = (String) bundle.get("nomeLocale");
		actionBar.setTitle(nomeLocale);
		setTitle(nomeLocale);
		mTitle = mDrawerTitle = nomeLocale;
		
		progressBar = (ProgressBar) findViewById(R.id.loading_locale_activity);
		
		if (!NetworkChecker.isInternetAvailable(getApplicationContext())) {
			NetworkChecker.noConnectionToast(getApplicationContext());
			return;
		}else{
			progressBar.setVisibility(View.VISIBLE);
			localeTask = (LocaleTask) new LocaleTask(this,this).execute();
			preferitiTask = (PreferitiTask) new PreferitiTask(this,this).execute();
		}

	}
	
	@Override
	public void onTaskComplete(Locale result) {

		try {
			locale = localeTask.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		if(preferitiTask.getStatus().equals(Status.FINISHED) && caricamento){
			caricamento = false;
			progressBar.setVisibility(View.GONE);
			findIfPreferito();
			instantiateFragments();
		}
	}
	
	@Override
	public void onTaskCompletePreferiti(List<Locale> result) {
		
		try {
			localiPreferiti = preferitiTask.get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		if(localeTask.getStatus().equals(Status.FINISHED) && caricamento){
			caricamento = false;
			progressBar.setVisibility(View.GONE);
			findIfPreferito();
			instantiateFragments();
		}
	}
	
	public void instantiateFragments(){		
		// Create the adapter that will return a fragment for each of the three
		// primary sections of the activity.
		mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());

		// Set up the ViewPager with the sections adapter.
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(mSectionsPagerAdapter);

		// When swiping between different sections, select the corresponding
		// tab. We can also use ActionBar.Tab#select() to do this if we have
		// a reference to the Tab.
		mViewPager
				.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
					@Override
					public void onPageSelected(int position) {
						actionBar.setSelectedNavigationItem(position);
					}
				});

		// For each of the sections in the app, add a tab to the action bar.
		for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
			// Create a tab with text corresponding to the page title defined by
			// the adapter. Also specify this Activity object, which implements
			// the TabListener interface, as the callback (listener) for when
			// this tab is selected.
			actionBar.addTab(actionBar.newTab()
					.setText(mSectionsPagerAdapter.getPageTitle(i))
					.setTabListener(this));
		}
		
	}
	/*
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.locale, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		super.onOptionsItemSelected(item);
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	*/
	@Override
	public void onTabSelected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {
		// When the given tab is selected, switch to the corresponding page in
		// the ViewPager.
		mViewPager.setCurrentItem(tab.getPosition());
	}

	@Override
	public void onTabUnselected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {
	}

	@Override
	public void onTabReselected(ActionBar.Tab tab,
			FragmentTransaction fragmentTransaction) {
	}

	/**
	 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
	 * one of the sections/tabs/pages.
	 */
	public class SectionsPagerAdapter extends FragmentPagerAdapter {

		public SectionsPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			// getItem is called to instantiate the fragment for the given page.
			// Return a PlaceholderFragment (defined as a static inner class
			// below).
			switch (position) {
				case 0:
				{
					return LocaleHomeFragment.newInstance(position + 1, locale, preferito);
				}
				case 1:
				{
					return LocaleMenuFragment.newInstance(position + 1, locale);
				}
				case 2:
				{
					return LocaleFotoFragment.newInstance(position + 1, locale);
				}
			}
			return null;
		}

		@Override
		public int getCount() {
			// Show 3 total pages.
			return 3;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			java.util.Locale l = java.util.Locale.getDefault();
			switch (position) {
			case 0:
				return getString(R.string.title_locale_section1).toUpperCase(l);
			case 1:
				return getString(R.string.title_locale_section2).toUpperCase(l);
			case 2:
				return getString(R.string.title_locale_section3).toUpperCase(l);
			}
			return null;
		}
	}
	
	private class LocaleTask extends AsyncTask<Void, Void, Locale> {

		private LocaleHomeTaskCompleteListener<Locale> callback;

		public LocaleTask(Context context, LocaleHomeTaskCompleteListener<Locale> cb)
		{
			this.callback = cb;
		}

		@Override
		protected Locale doInBackground(Void... params) {

			Localeendpoint.Builder builder1 = new Localeendpoint.Builder(
					AndroidHttp.newCompatibleTransport(), new JacksonFactory(),
					null);
			builder1 = CloudEndpointUtils.updateBuilder(builder1);
			builder1.setApplicationName("to-book");
			Localeendpoint endpointLocale = builder1.build();
			Locale localeGet = new Locale();
			
			try{
				localeGet = endpointLocale.findByJsonKey(idLocale).execute();
			}catch(IOException e){
				e.printStackTrace();		
			}
			return localeGet;
		}
		
		@Override
		protected void onPostExecute(Locale result) {
			
			callback.onTaskComplete(result);
		}
	}
	
	private class PreferitiTask extends AsyncTask<Void, Void, List<Locale>> {

		private LocaleHomeTaskPreferitiListener<List<Locale>> callback;
		
		public PreferitiTask(Context context, LocaleHomeTaskPreferitiListener<List<Locale>> cb)
		{
			this.callback = cb;
		}

		@Override
		protected List<Locale> doInBackground(Void... params) {

			Localeendpoint.Builder builder1 = new Localeendpoint.Builder(
					AndroidHttp.newCompatibleTransport(), new JacksonFactory(),
					null);
			builder1 = CloudEndpointUtils.updateBuilder(builder1);
			builder1.setApplicationName("to-book");
			Localeendpoint endpointLocale = builder1.build();
			List<Locale> locPreferiti = new ArrayList<Locale>();
			
			try{
				LocaleCollection locali = endpointLocale.findPreferitiUtente(emailUtente).execute();
				locPreferiti = locali.getItems();
				
			}catch(IOException e){
				e.printStackTrace();
				
			}
			return locPreferiti;
		}
		
		@Override
		protected void onPostExecute(List<Locale> result) {
			
			callback.onTaskCompletePreferiti(result);
		}
	}
	
	public void findIfPreferito(){
		
		if(localiPreferiti != null && localiPreferiti.size()>0){	
			for(Locale loc: localiPreferiti){
				if(loc.getId().getId().equals(locale.getId().getId())){
					preferito = true;
					break;
				}
			}
		}
	}

}
